package com.flmes.base.config;

import com.flmes.base.base.exception.TokenException;
import com.flmes.base.base.model.UserToken;
import com.flmes.base.constant.RequestConstant;
import com.flmes.base.service.AuthService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: flmes
 * @Date: 2024/9/27 19:25
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(RequestConstant.TOKEN);
        if (StringUtils.hasText(token)) {
            UserToken userToken = authService.getUserInfoByToken(token);
            // 存在正确的token
            if (Objects.nonNull(userToken)) {
                request.setAttribute(RequestConstant.USER_INFO, userToken);
                return true;
            }
        }
        throw new TokenException();
    }

}
